using System;
using System.Collections.Generic;

using Sce.PlayStation.Core.Input;
using Sce.PlayStation.HighLevel.UI;


using VitaReader;

namespace VitaReaderLibPS
{
	internal class PSControl : IReaderControl
	{
		private PSReader mOwner;
		
		public PSControl (PSReader owner)
		{
			mOwner = owner;
		}
		
		void IReaderControl.Initialize()
		{
			//UISystem.EnabledFocus = false;
			//UISystem.SuppressFocusKeyEvent = true;
			UISystem.KeyRepeatIntervalTime = 0;
			UISystem.KeyRepeatStartTime = 0;
			UISystem.EnabledFocus = false;
		}
		
		void IReaderControl.Update()
		{
			// Query gamepad for current state
			GamePadData gamePadData = GamePad.GetData (0);
			
			// Query touch for current state
            List<TouchData> touchDataList = Touch.GetData(0);

            // Update UI Toolkit
			
			//try
			{
            	UISystem.Update(touchDataList, ref gamePadData);
			}
			//catch(Exception e)
			{
			}
		}
		
		void IReaderControl.Shutdown()
		{
		}
		
		void IReaderControl.Exit()
		{
			mOwner.Terminate();
		}
		
		DragType IReaderControl.DetectDrag(float x,float y)
		{
			//detect horizontal drage to move to mainmenu/bookmarks(like the R/L)
			float DeltaY = Math.Abs(y);
			float DeltaX = Math.Abs(x);
			
			const float cot10 = 5.67f;
			const float tan80 = cot10;
			
			if( DeltaY <= 25.0f && DeltaX >= 40.0f
			   || DeltaY >= 25.0f && DeltaX/DeltaY >= cot10 )
			{
				if( x > 0 )
					return DragType.RIGHT;
				else
					return DragType.LEFT;
			}
			else if( DeltaX <= 25.0f && DeltaY >= 40.0f
			   || DeltaX >= 25.0f && DeltaY/DeltaX >= tan80 )
			{
				if( y > 0 )
					return DragType.UP;
				else
					return DragType.DOWN;
			}
			return DragType.NONE;
		}
		
		IReader IReaderControl.Owner
		{
			get	{ return mOwner as PSReader;}
		}
	}
}

